<template>
  <j-modal
    :confirmLoading="confirmLoading"
    :title="title"
    :visible="visible"
    :width="800"
    switchFullscreen
    cancelText="关闭"
    @cancel="handleCancel"
    @ok="handleOk">
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button v-if="!disableSubmit" type="primary" @click="handleOk">确认</a-button>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-col :md="11" :sm="24">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="拜访类型"
          >
            <a-select
              v-decorator="['visitType',validatorRules.visitType]"
              :disabled="disableSubmit" placeholder="请选择"
            >
              <a-select-option value="1">
                拜访
              </a-select-option>
              <a-select-option value="2">
                协访
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="13" :sm="24">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="客户类型"
            style="margin-right: 10px;"
          >
            <a-select
              v-decorator="['customerType',validatorRules.customerType]"
              :disabled="disableSubmit" placeholder="请选择"
            >
              <a-select-option value="2">
                经销商
              </a-select-option>
              <a-select-option value="1">
                门店
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-divider orientation="left" style="font-weight: 400;margin: 5px 0;">使用角色</a-divider>
        <div style="padding: 0px 20px;">
          <j-select-role placeholder="角色" :giveBackList="dataSource2"
                         :returnName="true" :inputs="false" search-icon="" select-button-text="新增"
                         list-url="/cnRoleController/getRoleList" :multiple="true"
                         @select="saveUserRelation"
                         :disabled="disableSubmit"/>
        </div>
        <div style="padding: 10px 20px;">
          <a-table size="small" bordered row-key="idst" :columns="columns" :dataSource="dataSource2"
                   :rowSelection="{ selectedRowKeys:selectedRowKeys2, onChange: onSelectChange}"
                   :scroll="{x:400,y:240 }"
                   @change="handleTableChange">
            <span slot="action" slot-scope="text, record,index">
              <a style="color: red;" @click="handleDelete(record,index)" v-if="!disableSubmit">删除</a>
            </span>
          </a-table>
        </div>
        <a-divider orientation="left" style="font-weight: 400;margin-top: 0px;">拜访步骤</a-divider>

        <a-table
          bordered
          size="small"
          row-key="key"
          :columns="columns3"
          :dataSource="dataSources3"
          :pagination="false"
          :scroll="{x:400,y:240 }"
          @edit-disabled="editDisabledEvent"
        >
          <template slot="dictDataDesc" slot-scope="text, record,index">
            <a-select :disabled="title=='详情' ||disableSubmit||index==dataSources3.length-1||index==0"
                      :value="record.callStepsContentName" default-value=""
                      placeholder="请选择步骤"
                      style="width:100%" @change="giveValue('type',record,$event)">

              <a-select-option v-for="(item, key) in dictOptions" :key="key" :value="item.dictDataDesc">
                  <span style="display: inline-block;width: 100%"
                        :title=" item.dictDataDesc || item.callStepsContentName ">
                  {{ item.dictDataDesc || item.callStepsContentName }}
                  </span>
              </a-select-option>
            </a-select>
          </template>

          <template slot="isItNecessary" slot-scope="text, record,index">
            <a-select :disabled="title=='分账详情' ||disableSubmit||index==dataSources3.length-1||index==0"
                      :value="record.isItNecessary" default-value="" placeholder="请选择类目"
                      style="width:100%" @change="giveitValue('type',record,$event)">
              <a-select-option v-for="(item, key) in dictOptCode" :key="key" :value="item.name">
                  <span style="display: inline-block;width: 100%" :title=" item.name || item.isItNecessary ">
                  {{ item.name || item.isItNecessary }}
                  </span>
              </a-select-option>
            </a-select>
          </template>
          <template slot="sort" slot-scope="text, record,index">
            <a :disabled="disableSubmit||index>=dataSources3.length-2||index==0" @click="moveUp(record,index,1)">下移</a>
            <a-divider type="vertical"/>
            <a :disabled="disableSubmit || index<=1 ||index==dataSources3.length-1"
               @click="moveUp(record,index,2)">上移</a>
          </template>
          <template slot="action" slot-scope="text, record, index">
            <a :disabled="disableSubmit||index==dataSources3.length-1||index==0" @click="handleDelete2(record)">删除</a>
          </template>
        </a-table>

        <a-button v-show="title != '分账详情'" :disabled="disableSubmit" class="editable-add-btn"
                  v-if="this.dataSources3.length<this.dictOptionsList.length+2"
                  @click="handleAdd" style="margin-bottom: 8px"
                  type="primary">
          +添加一行
        </a-button>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import { httpAction } from '@/api/manage'
import pick from 'lodash.pick'
import { getAction, postAction } from '@/api/manage'
import JSelectRole from '@comp/cn-select-popup/JSelectRole'

export default {
  name: 'SfaVisitDisplayModal',
  components: {
    JSelectRole,
  },
  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      unicodess: [],
      dictOptions: [],
      dictOptionsList: [],
      dictOptid: 1,
      dataSource: [],
      dataSource2: [],
      dataSources3: [],
      dictOptCode: [
        {
          name: '是',
          id: 1
        },
        {
          name: '否',
          id: 2
        }
      ],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      count: 0,
      columns: [{
        title: '角色编号',
        align: 'center',
        dataIndex: 'roleCode'
      },
        {
          title: '角色名称',
          align: 'center',
          dataIndex: 'roleName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      columns3: [
        {
          title: '步骤名称',
          align: 'center',
          dataIndex: 'dictDataDesc',
          scopedSlots: { customRender: 'dictDataDesc' }
        },
        {
          title: '是否必做',
          align: 'center',
          dataIndex: 'isItNecessary',
          scopedSlots: { customRender: 'isItNecessary' }
        },
        {
          title: '拜访顺序',
          align: 'center',
          dataIndex: 'a',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '调整排序',
          align: 'center',
          scopedSlots: {
            customRender: 'sort'
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        visitType: { rules: [{ required: true, message: '请输入停用启用状态!' }] },
        customerType: { rules: [{ required: true, message: '经销商类型!' }] },
        saasid: { rules: [{ required: true, message: '请输入saasid!' }] }
      },
      url: {
        add: window._CONFIG['domianSfaURL'] + '/sfaCallStepsController/saveOrUpdate',
        edit: '/visit/sfaVisitDisplayEntity/edit'
      }
    }
  },
  created() {
    this.diction()
  },
  methods: {
    diction() {
      let that = this
      getAction(window._CONFIG['domianURL'] + `/cnDictionaryController/getDictByCode`, { dictCode: 'call_steps_content_name' }).then(res => {
        console.log(res)
        that.dictOptions = res.result
        that.dictOptionsList = JSON.parse(JSON.stringify(res.result))
      })
    },
    editDisabledEvent(row) {
      console.log('禁止编辑')
    },
    moveDown(record) {
      //交换数组元素
      let swapItems = function (arr, index1, index2) {
        arr[index1] = arr.splice(index2, 1, arr[index1])[0]
        return arr
      }
      let i = this.dataSource.length
      while (i--) {
        if (this.dataSource[i] == record) {
          this.dataSource = swapItems(this.dataSource, i, i + 1)
          console.log(i, this.dataSource)
        }
      }
    },
    handleAdd() {
      const { count, dataSources3 } = this
      // console.log(this.dataSources3)
      const newData = {
        key: count,
        dictDataDesc: '',
        isItNecessary: "是",
        // callStepsContentCode: dataSources3.length + 1,
        id: ''
        // name: '',
        // scaleNum: '',
        // serviceCharge: '0'
      }
      this.dictOptid++
      this.dataSources3 = []
      this.dataSources3 = [...dataSources3, newData]
      this.dataSources3.sort((a, b) => b.callStepsContentName == '离店打卡' ? -1 : 0)
      // this.count = count + 1
    },
    // 上移
    moveUp(record, index, type) {
      let indexs = index
      if (type == 1) {
        indexs = index == this.dataSources3.length - 1 ? 0 : index + 1
      } else {
        indexs--
      }
      this.dataSources3[index] = this.dataSources3.splice(indexs, 1, this.dataSources3[index])[0]
    },
    giveValue(key, obj, e) {
      let item = this.dictOptionsList.find(v => v.dictDataDesc == e)
      let num = this.dataSources3.indexOf(obj)
      console.log(obj)
      obj[key] = e
      obj['callStepsContentName'] = item.dictDataDesc
      obj['callStepsContentCode'] = item.dictDataCode
      this.$set(this.dataSources3, num, obj)
      let options = []
      console.log(item)
      this.dictOptionsList.forEach(item => {
        let index = this.dataSources3.findIndex(v => v.callStepsContentName == item.dictDataDesc)
        if (index == -1) {
          options.push(item)
        }
      })
      this.dictOptions = options
    },
    giveitValue(key, obj, e) {
      console.log(key, obj, e)
      let item = this.dictOptCode.find(v => v.isItNecessary == e)
      let num = this.dataSources3.indexOf(obj)
      this.$set(this.dataSources3, num, obj)
      obj['isItNecessary'] = e
    },

    saveUserRelation(e) {
      this.dataSource2 = []
      let key = this.dataSource2.map(item => {
        return item.roleCode
      })
      console.log(e)
      let that = this
      e.forEach(item => {
        if (key.indexOf(item.roleCode) == -1) {
          item.code = item.roleCode
          item.name = item.roleName
          this.dataSource2.push(item)
        }
      })
    },
    handleDelete(record, index) {
      this.dataSource2.splice(index, 1)
    },
    handleDelete2(key) {
      key.dictDataDesc = key.callStepsContentName
      const dataSurces3 = [...this.dataSources3]
      this.dataSources3 = dataSurces3.filter(item => item !== key)
      this.originRule = ''
      if (key.dictDataDesc) {
        this.dictOptions.push(key)
      }
    },
    add() {
      this.edit({})
    },
    edit(record) {

      // this.diction()
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.dataSources3 = record.contentVos || []
      this.dataSource2 = record.roleVos || []
      this.visible = true

      for (let i = 0; i < this.dataSources3.length; i++) {
        if (this.dataSources3[i].isItNecessary == 1) {
          this.dataSources3[i].isItNecessary = '是'
        } else if (this.dataSources3[i].isItNecessary == 0) {
          this.dataSources3[i].isItNecessary = '否'
        }
      }
      for (let y = 0; y < this.dataSources3.length; y++) {
        for (let s = 0; s < this.dictOptions.length; s++) {
          if (this.dictOptions[s].dictDataDesc == this.dataSources3[y].callStepsContentName) {
            this.dictOptions.splice(s, 1)
          }
        }
      }
      console.log(record)
      if (Object.keys(record).length == 0) {
        this.dataSources3.unshift({
          callStepsContentCode: '1',
          callStepsContentName: '进店打卡',
          dictDataDesc: '',
          id: '',
          isItNecessary: '是',
          key: 0,
          type: '进店打卡',
        })
        this.dataSources3.push({
          callStepsContentCode: '2',
          callStepsContentName: '离店打卡',
          dictDataDesc: '',
          id: '',
          isItNecessary: '是',
          key: 0,
          type: '离店打卡',
        })
      }
      console.log(this.dataSources3)
      // this.giveValue()
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'roleVos', 'visitType', 'visitTypeStr', 'orgCode', 'orgName', 'customerType', 'customerTypeStr', 'contentVos', 'orgCode', 'orgName', 'status', 'deleteStatus', 'remarks', 'saasid', 'visitId', 'visitType', 'displayType', 'displayUrl'))
        //时间格式化
      })
    },
    close() {
      this.$emit('close')
      this.diction()
      this.visible = false
      this.dataSource2 = []
      this.dataSource = []
      this.dataSources3 = []
    },
    handleOk() {
      const that = this
      // 触发表单验证
      for (let i = 0; i < this.dataSources3.length; i++) {
        this.dataSources3[i].callStepsContentCode = this.dataSources3[i].callStepsContentCode
        this.dataSources3[i].callStepsContentName = this.dataSources3[i].callStepsContentName
        if (this.dataSources3[i].isItNecessary == '是') {
          this.dataSources3[i].isItNecessary = 1
        } else if (this.dataSources3[i].isItNecessary == '否') {
          this.dataSources3[i].isItNecessary = 0
        }
      }
      console.log(that.unicodess)
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.add
            method = 'post'
          }
          let formData = Object.assign(this.model, values)
          //时间格式化
          formData.contentVos = this.dataSources3
          formData.roleVos = this.dataSource2
          console.log(formData)
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })
        }
      })
    },
    handleCancel() {
      this.close()
    }

  }
}
</script>

<style lang="less" scoped>
</style>